import React, { useState } from 'react'

export default function App() {
    const [content, setContent] = useState('')
    const [question, setQuestion] = useState('讲一下龟兔赛跑的故事,200字以内')
    const [streaming, setStreaming] = useState(false)

    const update = async () => {
        if (!question) return
        setContent('思考中...')
        const endpoint = '/api/stream'  // 代理后的后端接口
        if (streaming) {
            setContent('')
            const eventSource = new EventSource(`${endpoint}?question=${question}`)// 建立SSE连接
            eventSource.addEventListener('message', (e) => {
                //后端每响应一次，就会触发message事件
                setContent((pre)=>pre+e.data)  // 接收后端返回的消息并更新状态
            })
            eventSource.addEventListener('end', () => {
                eventSource.close()
            })
        }
    }
    return (
        <div className='container'>
            <div>
                <label>输入：</label>
                <input type="text" defaultValue={question} onChange={(e) => setQuestion(e.target.value)} />
                <button onClick={update}>提交</button>
            </div>

            <div className="output" style={{ minHeight: '300px', width: '500px' }}>
                <div>
                    <label>Streaming</label>
                    <input type="checkbox" onChange={(e) => setStreaming(e.target.checked)} />
                    <div>{content}</div>
                </div>
            </div>
        </div>
    )
}